package main

import (
	"fmt"
	"time"
)

func main() {
	/*writeCh := make(chan int)
	exitCh := make(chan bool)
	go ReadData(writeCh, exitCh)
	go WriteData(writeCh)
	isOver := <-exitCh
	if isOver {
		fmt.Println("读取结束")
	}*/

	ch := make(chan int, 1)
	writeCh := chan<- int(ch)
	writeCh <- 1
	readCh := <-chan int(ch)
	fmt.Println(writeCh)
	fmt.Printf("%T", readCh)
	//overCh := make(chan bool)
	//go singleRead(ch, overCh)
	//go singleWrite(ch)
	//if <-overCh {
	//	fmt.Println("over")
	//}

}

func singleWrite(ch chan<- int) {
	for i := 0; i < 10; i++ {
		ch <- i
	}
	close(ch)
}

//只读取数据
func singleRead(ch <-chan int, overCh chan<- bool) {
	for {
		msg, ok := <-ch
		if !ok {
			overCh <- true
			break
		}
		fmt.Println("read data:", msg)
	}
}

//单向channel
func singleChannel() {
	// 只写 channel
	writeChan := make(chan<- int, 3)
	writeChan <- 3
	writeChan <- 2
	writeChan <- 1
	fmt.Println(writeChan)
	//不可以读
	//msg:=<-writeChan

	//只读 channel
	readChan := make(<-chan int, 3)
	msg := <-readChan
	fmt.Println(msg)
	//不可写
	//readChan<-3
}
func blockTest() {
	ch := make(chan int, 1)
	msg := <-ch
	fmt.Println(msg)

}

func ReadData(ch chan int, exitCh chan bool) {
	time.Sleep(time.Second * 5)
	for {
		msg, ok := <-ch
		if !ok {
			exitCh <- true
			break
		}
		fmt.Println("read data:", msg)

	}
}

func WriteData(ch chan int) {
	for i := 0; i < 25; i++ {
		fmt.Println("write data:", i)
		ch <- i
	}
	close(ch)
}

func makeChannel() {
	// 声明一个接收 int 类型的管道
	var ch1 chan int
	//nil 因为没有分配空间
	fmt.Println(ch1)

	//创建一个 string 类型的管道
	ch2 := make(chan string)
	//0xc000062060
	fmt.Println(ch2)
	//创建指定长度的 channel
	ch3 := make(chan string, 3)
	//0xc000056180
	fmt.Println(ch3)
}

func writeAndRead() {
	ch := make(chan string, 3)

	//写入一个消息
	ch <- "haha"
	fmt.Printf("ch 长度:%v,容量:%v\n", len(ch), cap(ch))
	msg := <-ch

	fmt.Println("收到的消息:", msg)
	msg2 := <-ch
	fmt.Println("msg2:", msg2)

}
